<template>
  <div class="flex h-screen overflow-hidden bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-200">
    <!-- 侧边栏 -->
    <Sidebar @select-query="handleSidebarQuery" @show-training="showTrainingPage = true" @show-main="showMainPage" />

    <!-- 通知组件 -->
    <Notification
      v-if="notification.show"
      :title="notification.title"
      :message="notification.message"
      :type="notification.type"
      :duration="notification.duration"
      @close="closeNotification"
    />

    <!-- 主内容区 -->
    <main class="flex-1 overflow-y-auto ent-scrollbar">
      <div class="container mx-auto px-6 py-8">
        <header class="mb-8">
          <h1 class="text-3xl font-semibold text-gray-900 dark:text-white mb-2 flex items-center">
            <span class="text-primary-600 dark:text-primary-400">Text2SQL</span>
            <span class="ml-2 text-gray-500 dark:text-gray-400 text-xl">智能数据查询平台</span>
          </h1>
          <p class="text-gray-600 dark:text-gray-400">使用自然语言查询您的数据库，无需编写SQL代码</p>
        </header>

        <!-- 训练数据页面 -->
        <TrainingData v-if="showTrainingPage" />

        <!-- 查询输入区域和结果展示区域 -->
        <template v-else>
          <QueryInput
            :key="queryInputKey"
            v-model:query="queryInputValue"
            @submit-query="handleQuerySubmit"
            :loading="loading"
          />

          <div class="mt-8 grid grid-cols-1 gap-8">
            <ResultDisplay
              v-if="queryResult"
              :result="queryResult"
              :sql="generatedSQL"
              :loading="loading"
              :query-id="currentQueryId"
            />

            <PlotlyChart
              v-if="chartData"
              :chart-data="chartData"
              :loading="chartLoading"
            />
          </div>
        </template>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import Sidebar from './components/Sidebar.vue'
import QueryInput from './components/QueryInput.vue'
import ResultDisplay from './components/ResultDisplay.vue'
import PlotlyChart from './components/PlotlyChart.vue'
import Notification from './components/Notification.vue'
import TrainingData from './components/TrainingData.vue'

export default {
  name: 'App',
  components: {
    Sidebar,
    QueryInput,
    ResultDisplay,
    PlotlyChart,
    Notification,
    TrainingData
  },
  setup() {
    const loading = ref(false)
    const chartLoading = ref(false)
    const queryResult = ref(null)
    const generatedSQL = ref('')
    const chartData = ref(null)
    const currentQueryId = ref(null)
    const showTrainingPage = ref(false)
    const queryInputKey = ref(Date.now())
    const queryInputValue = ref('')

    // 通知状态
    const notification = reactive({
      show: false,
      title: '',
      message: '',
      type: 'info',
      duration: 3000
    })

    // 显示通知
    const showNotification = (title, message, type = 'info', duration = 3000) => {
      notification.title = title
      notification.message = message
      notification.type = type
      notification.duration = duration
      notification.show = true
    }

    // 关闭通知
    const closeNotification = () => {
      notification.show = false
    }
    
    // 显示主页
    const showMainPage = () => {
      showTrainingPage.value = false
    }

    // 处理侧边栏查询
    const handleSidebarQuery = (query) => {
      queryInputValue.value = query
      queryInputKey.value = Date.now()
      showTrainingPage.value = false
    }

    const handleQuerySubmit = async (query) => {
      if (!query.trim()) return

      loading.value = true
      queryResult.value = null
      generatedSQL.value = ''
      chartData.value = null

      try {
        // 步骤1: 生成SQL
        showNotification('处理中', '正在生成SQL查询...', 'info')

        const sqlResponse = await fetch(`/api/v0/generate_sql?question=${encodeURIComponent(query)}`)
        const sqlData = await sqlResponse.json()

        // 检查响应格式 - 兼容两种返回格式
        let sqlResponseData, queryId, sqlText
        if (sqlData.code && sqlData.code === 200 && sqlData.data) {
          // 包装模式 (R.ok 返回的格式)
          sqlResponseData = sqlData.data
          queryId = sqlResponseData.id
          sqlText = sqlResponseData.text
        } else if (sqlData.type === 'sql') {
          // 直接返回模式 (FastAPI 原生返回)
          sqlResponseData = sqlData
          queryId = sqlData.id
          sqlText = sqlData.text
        } else {
          throw new Error(sqlData.message || sqlData.detail || '生成SQL失败')
        }

        currentQueryId.value = queryId
        generatedSQL.value = sqlText

        // 步骤2: 执行SQL
        showNotification('处理中', '正在执行SQL查询...', 'info')

        const runResponse = await fetch(`/api/v0/run_sql?id=${queryId}`)
        const runData = await runResponse.json()

        // 检查响应格式 - 兼容两种返回格式
        let resultData
        if (runData.code && runData.code === 200 && runData.data) {
          // 包装模式
          resultData = runData.data.df ? JSON.parse(runData.data.df) : null
        } else if (runData.type === 'df' && runData.df) {
          // 直接返回模式
          resultData = JSON.parse(runData.df)
        } else {
          throw new Error(runData.message || runData.detail || '执行SQL失败')
        }

        // 解析结果数据
        if (resultData) {
          queryResult.value = resultData
        }

        // 步骤3: 生成图表
        await generateChart(queryId)

        // 查询成功通知
        showNotification('查询成功', '已成功执行查询并生成结果', 'success')

      } catch (error) {
        showNotification('查询失败', error.message || '执行查询时发生错误', 'error', 5000)
      } finally {
        loading.value = false
      }
    }

    const generateChart = async (id) => {
      if (!id) return

      chartLoading.value = true

      try {
        showNotification('处理中', '正在生成数据可视化...', 'info')

        const response = await fetch(`/api/v0/generate_plotly_figure?id=${id}`)
        const data = await response.json()

        // 检查各种可能的响应格式
        if (data.code && data.code === 200 && data.data && data.data.fig) {
          // 包装模式 (R.ok)
          try {
            chartData.value = typeof data.data.fig === 'string' ? JSON.parse(data.data.fig) : data.data.fig
          } catch (e) {
            chartData.value = { data: data.data.fig }
          }
        } else if (data.type === 'plotly' && data.fig) {
          // 直接返回模式 (FastAPI)
          try {
            chartData.value = typeof data.fig === 'string' ? JSON.parse(data.fig) : data.fig
          } catch (e) {
            chartData.value = { data: data.fig }
          }
        } else if (data.fig || data.figure || data.chart) {
          // 其他可能的格式
          const figData = data.fig || data.figure || data.chart
          try {
            chartData.value = typeof figData === 'string' ? JSON.parse(figData) : figData
          } catch (e) {
            chartData.value = { data: figData }
          }
        } else {
          // 无法获取到图表数据，创建一个默认图表
          
          // 尝试从查询结果创建图表
          if (queryResult.value) {
            chartData.value = createDefaultChartFromQueryResult(queryResult.value)
          } else {
            chartData.value = createEmptyChart()
          }
        }
      } catch (error) {
        showNotification('提示', '生成图表时出错，但不影响数据查询结果', 'warning')
        
        // 尝试从查询结果创建图表
        if (queryResult.value) {
          chartData.value = createDefaultChartFromQueryResult(queryResult.value)
        }
      } finally {
        chartLoading.value = false
      }
    }
    
    // 从查询结果创建默认图表
    const createDefaultChartFromQueryResult = (result) => {
      try {
        // 尝试找到查询结果中的数据字段
        if (!result || !result.fields || !result.records || result.records.length === 0) {
          return createEmptyChart()
        }
        
        const fields = result.fields
        const records = result.records
        
        // 找出数值类型的字段和非数值类型的字段
        const numericFields = []
        const categoryFields = []
        
        fields.forEach(field => {
          // 判断字段类型
          const fieldValues = records.map(record => record[field])
          const isNumeric = fieldValues.every(value => 
            value === null || value === undefined || 
            (typeof value === 'number' && !isNaN(value)) ||
            (typeof value === 'string' && !isNaN(Number(value)))
          )
          
          if (isNumeric) {
            numericFields.push(field)
          } else {
            categoryFields.push(field)
          }
        })
        
        // 确定图表类型
        let chartType = 'bar'
        let xField = categoryFields[0] || fields[0]
        let yField = numericFields[0] || fields[1] || fields[0]
        
        // 如果没有分类字段，使用第一个字段作为X轴
        if (categoryFields.length === 0 && fields.length > 1) {
          xField = fields[0]
          yField = fields[1]
        }
        
        // 创建图表数据
        const xValues = records.map(record => record[xField])
        const yValues = records.map(record => record[yField])
        
        return {
          data: [
            {
              type: chartType,
              x: xValues,
              y: yValues,
              marker: {
                color: '#0066c8'
              }
            }
          ],
          layout: {
            title: `${yField} 按 ${xField} 统计`,
            showlegend: false,
            xaxis: {
              title: xField
            },
            yaxis: {
              title: yField
            }
          }
        }
      } catch (error) {
        return createEmptyChart()
      }
    }
    
    // 创建空图表
    const createEmptyChart = () => {
      return {
        data: [
          {
            type: 'bar',
            x: ['数据1', '数据2', '数据3', '数据4', '数据5'],
            y: [10, 15, 13, 17, 12],
            marker: {
              color: '#0066c8'
            }
          }
        ],
        layout: {
          title: '默认数据图表',
          showlegend: false
        }
      }
    }

    return {
      loading,
      chartLoading,
      queryResult,
      generatedSQL,
      chartData,
      currentQueryId,
      showTrainingPage,
      queryInputKey,
      queryInputValue,
      notification,
      showNotification,
      closeNotification,
      handleQuerySubmit,
      showMainPage,
      handleSidebarQuery
    }
  }
}
</script>

<style>
/* 企业级UI动画效果 */
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>
